package com.cccyy.date;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DiffMonth {
    public static void main(String[] args) throws ParseException {

        SimpleDateFormat yyyyMMdd = new SimpleDateFormat("yyyyMMdd");
        Date billDate = yyyyMMdd.parse("20231205");//账单日期
        //获取账单日期中的日
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(billDate);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        calendar.setTime(new Date());
        int dayNow = calendar.get(Calendar.DAY_OF_MONTH);

        if (dayNow >= day) {
            System.out.println("需要从本月开始计数");
        }else {
            System.out.println("需要从上月开始计数");
        }

//        历史账单查询月份  yyyyMM
        Date queryDate = yyyyMMdd.parse("202312" + day);//账单日期
        int i = diffMonth(billDate, queryDate);
        System.out.println("计算出的月份差值为：" + i);
    }

    public static int diffMonth(Date d1, Date d2) {
        Calendar c1 = Calendar.getInstance();
        c1.setTime(d1);
        Calendar c2 = Calendar.getInstance();
        c2.setTime(d2);

        int m = c1.get(Calendar.MONTH) - c2.get(Calendar.MONTH);
        int y = c1.get(Calendar.YEAR) - c2.get(Calendar.YEAR);
        return y * 12 + m;
    }
}
